package com.shunan.miaosha.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.shunan.miaosha.beans.Users;
import com.shunan.miaosha.redis.RedisService;
import com.shunan.miaosha.service.GoodsService;
import com.shunan.miaosha.service.UserService;
import com.shunan.miaosha.vo.GoodsVo;

@Controller
@RequestMapping("/goods")
public class GoodsController {
	
	@Autowired	
	private UserService userService;
	@Autowired
	private RedisService redisService;
	@Autowired
	private GoodsService goodsService;
	
	@RequestMapping("/to_list")
	public String to_list(Model model, Users users){
		model.addAttribute("user", users);
		List<GoodsVo> list=goodsService.listGoodsVo();
		model.addAttribute("goodsList", list);	
		return "goods_list";
	}
	@RequestMapping("/to_detail/{id}")
	public String to_detail(Model model, Users users,@PathVariable int id){
		model.addAttribute("user", users);
		GoodsVo goods = goodsService.getGoodsVoByGoodsId(id);
		model.addAttribute("goods", goods);	
		
		long startAt = goods.getStartDate().getTime();
    	long endAt = goods.getEndDate().getTime();
    	long now = System.currentTimeMillis();
    	
    	int miaoshaStatus = 0;
    	int remainSeconds = 0;
    	if(now < startAt ) {//秒杀还没开始，倒计时
    		miaoshaStatus = 0;
    		remainSeconds = (int)((startAt - now )/1000);
    	}else  if(now > endAt){//秒杀已经结束
    		miaoshaStatus = 2;
    		remainSeconds = -1;
    	}else {//秒杀进行中
    		miaoshaStatus = 1;
    		remainSeconds = 0;
    	}
    	model.addAttribute("miaoshaStatus", miaoshaStatus);
    	model.addAttribute("remainSeconds", remainSeconds);
		
		return "goods_detail";
	}
}
